<template>
  <div class="card">
    <h3>
      <span>短链分组</span>
      <div class="btn">
        <Button icon="pi pi-plus" label="添加分组" severity="info" @click="addgroup()" />
        <Button icon="pi pi-refresh" label="Reload" severity="warning" @click="reloadgroup()" :loading="store.state.GroupsShort.isloading" />
      </div>
    </h3>
    <div class="header">
      <div class="name">组名</div>
      <div class="createtime">时间</div>
      <div class="action">操作</div>
    </div>
    <GroupItem v-for="(item) of store.state.GroupsShort.data" :key="item.id" :item="item"></GroupItem>
  </div>
  <!-- 消息提示 -->
  <Toast />
  <!-- 确认框 -->
  <ConfirmDialog></ConfirmDialog>
  <!-- 添加信息框 -->
  <Dialog v-model:visible="dialogvisible" modal header="添加短链" :style="{ width: '45rem' }">
    <span class="p-text-secondary block mb-5">输入短链链信息</span>
    <div class="flex align-items-center gap-3 mb-3">
      <label for="username" class="font-semibold w-6rem">链接</label>
      <InputText id="username" class="flex-auto" autocomplete="off" v-model="shortlink" />
    </div>
    <div class="flex justify-content-end gap-2">
      <Button type="button" label="Cancel" severity="secondary" @click="dialogvisible = false"></Button>
      <Button type="button" label="Save" @click="toaddshort()"></Button>
    </div>
  </Dialog>
</template>

<script setup>
import { ref, onMounted, provide } from 'vue'
import axios from 'axios';
import ConfirmDialog from 'primevue/confirmdialog';
import Toast from 'primevue/toast';
import Dialog from 'primevue/dialog';
import GroupItem from './GroupItem.vue';
import { useConfirm } from "primevue/useconfirm";
import { useToast } from "primevue/usetoast";
import InputText from 'primevue/inputtext';
import Button from 'primevue/button';
import { useStore } from 'vuex';

const store = useStore();

const confirm = useConfirm();
const toast = useToast();

function reloadgroup(){
  store.dispatch('getGroupShort')
}


// 添加组
function addgroup(){
  axios.get("https://api.cxkqun.com/index.php/api/groups/groups?auth=cxkqun&action=create").then(res => {
    if (res.data.code) {
      toast.add({ severity: 'info', summary: '创建成功', detail: `新建分组添加成功`, life: 3000 });
    } else {
      toast.add({ severity: 'error', summary: '创建失败', detail: `新建分组添加成功失败`, life: 3000 });
    }
    store.dispatch('getGroupShort')
  })
}


// 删除组元素
function deleteshort(data){
  confirm.require({
    message: `是否从该组删除：https://cxkqun.xyz/${data.short_code}`,
    header: '删除确认',
    icon: 'pi pi-info-circle',
    rejectLabel: '取消',
    acceptLabel: '删除',
    rejectClass: 'p-button-secondary p-button-outlined',
    acceptClass: 'p-button-danger',
    accept: () => {
      axios.get("https://api.cxkqun.com/index.php/api/groups/short",{
        params:{
          'auth':'cxkqun',
          'action':'delete',
          'id':data.id
        }
      }).then(res => {
        if(res.data.code){
          toast.add({ severity: 'info', summary: '删除成功', detail: `https://cxkqun.xyz/${data.short_code}成功删除`, life: 3000 });
        }else{
          toast.add({ severity: 'error', summary: '删除失败', detail: `https://cxkqun.xyz/${data.short_code}删除失败`, life: 3000 });
        }
        store.dispatch('getGroupShort')   
      })
    },
  });
}


// 删除该组
function deletegroup(data){
  confirm.require({
    message: `是否删除组：${data.group_name}`,
    header: '删除确认',
    icon: 'pi pi-info-circle',
    rejectLabel: '取消',
    acceptLabel: '删除',
    rejectClass: 'p-button-secondary p-button-outlined',
    acceptClass: 'p-button-danger',
    accept: () => {
      axios.get("https://api.cxkqun.com/index.php/api/groups/groups",{
        params:{
          'auth':'cxkqun',
          'action':'delete',
          'idgroup':data.id
        }
      }).then(res => {
        if(res.data.code){
          toast.add({ severity: 'info', summary: '删除成功', detail: `${data.group_name}成功删除`, life: 3000 });
        }else{
          toast.add({ severity: 'error', summary: '删除失败', detail: `${data.group_name}删除失败`, life: 3000 });
        }
        store.dispatch('getGroupShort')    
      })
    },
  });
}

// 更新组名
function updatename(data){
  if(data.newname === data.group_name){
    toast.add({ severity: 'error', summary: '取消修改', detail: '新旧名称相同', life: 3000 });
    return;
  }
  confirm.require({
    message: `是否建组名修改为：${data.newname}`,
    header: '修改确认',
    icon: 'pi pi-exclamation-triangle',
    rejectClass: 'p-button-secondary p-button-outlined',
    rejectLabel: '取消',
    acceptLabel: '确认',
    accept: () => {
      axios.get("https://api.cxkqun.com/index.php/api/groups/groups",{
        params:{
          'auth':'cxkqun',
          'action':'update',
          'idgroup':data.id,
          'newname':data.newname
        }
      }).then(res => {
        if(res.data.code){
          toast.add({ severity: 'info', summary: '修改成功', detail: `组名已修改为：${data.newname}`, life: 3000 });
        }else{
          toast.add({ severity: 'error', summary: '修改失败', detail: '新旧名称相同', life: 3000 });
        }
        store.dispatch('getGroupShort')
      })
      
    }
  });
}

// 给组添加短链
const dialogvisible = ref(false);
const shortlink = ref()
const tempdata = ref()
function addshort(data){
  dialogvisible.value = !dialogvisible.value
  tempdata.value = data
}
function toaddshort(){
  const url = shortlink.value;
  const uri = url.split('/').pop();
  const exists = tempdata.value.groupshort.some(group => group.short_code === uri);
  if(exists){
    toast.add({ severity: 'error', summary: '添加失败', detail: `重复添加`, life: 3000 });
    dialogvisible.value = !dialogvisible.value
    return
  }
  axios.get("https://api.cxkqun.com/index.php/api/groups/short",{
    params:{
      'auth':'cxkqun',
      'action':'create',
      'idgroup':tempdata.value.id,
      'short_code':uri
    }
  }).then(res => {
    if(res.data.code){
      toast.add({ severity: 'info', summary: '添加成功', detail: `${shortlink.value}添加成功`, life: 3000 });
    }else{
      toast.add({ severity: 'error', summary: '添加失败', detail: `${shortlink.value}添加失败`, life: 3000 });
    }
    dialogvisible.value = !dialogvisible.value
    store.dispatch('getGroupShort')
  })
}

// 使用 provide 函数提供函数
provide('updatename', updatename);
provide('deleteshort', deleteshort);
provide('addshort', addshort);
provide('deletegroup', deletegroup);
</script>

<style scoped lang="less">
    .card{
        width: calc(100% - 1rem);
        height: 100%;
        border: 1px solid #e2e8f0;
        margin-right: 1rem;
        &>h3{
          text-align: center;
          &>.btn{
            width: 100%;
            display: flex;
            justify-content: space-between;
          }
        }
        &>.header{
          display: flex;
          border-bottom: 1px solid #e2e8f0;
          &>*{
            flex: 1;
            font-weight: 600;
            padding-left: 10px;
            line-height: 60px;
          }

        }
    }
</style>